#include "precomp.h"
#include "Tgame.h"

void Tgame::start(const std::vector<CL_String> &args)
{
	quit = false;

	CL_Size screen_size(800, 600);

	create_window(screen_size);

	CL_GraphicContext gc = window.get_gc();
	CL_InputDevice keyboard = window.get_ic().get_keyboard();
	
	unsigned int last_time = CL_System::get_time();

	/*CL_FontDescription desc;
	desc.set_typeface_name("tahoma");
	desc.set_height(32);
	desc.set_subpixel(true);
	CL_Font font(gc, desc);*/


	T2d_Skeleton2d test_skeleton;

	T2d_Node2d_data def;
	def.set_main_prop(1, T2d_vec(0,0), T2d_vec(0,0),T2d_vec(0,0),1,0);
	def.set_length(5);
	def.position.set(10, 10);
	int node_0 = test_skeleton.add_node(def);
	int node_start = node_0;
	def.position+=T2d_vec(10,10);
	for(int i=0;i<10;i++)
	{def.set_length(20);
		int node_1 = test_skeleton.add_node(def, node_0);
		int node_00, node_11 = node_1;
		for(int i=0;i<10;i++)
		{def.set_length(5);
			node_00 = test_skeleton.add_node(def, node_11);
			node_11 = node_00;
		}
		node_0 = node_1;
	}
	test_skeleton.set_position(T2d_vec(200,200));


	for(int i=0;i<test_skeleton.get_node_count();i++)
		{
			CL_Console::write_line("%1 %2",i, test_skeleton.get_node_children_count(i));
			
		}
	while (!quit)
	{
		if (keyboard.get_keycode(CL_KEY_ESCAPE))
			break;

		if (keyboard.get_keycode(CL_KEY_UP))
		{
			test_skeleton.apply_node_impulse(node_start, T2d_vec(0,-10));
		}
		if (keyboard.get_keycode(CL_KEY_DOWN))
		{
			test_skeleton.apply_node_impulse(node_start, T2d_vec(0,10));
		}
		if (keyboard.get_keycode(CL_KEY_LEFT))
		{
			test_skeleton.apply_node_impulse(node_start, T2d_vec(-10,0));
		}
		if (keyboard.get_keycode(CL_KEY_RIGHT))
		{
			test_skeleton.apply_node_impulse(node_start, T2d_vec(10,0));
		}

		unsigned int current_time = CL_System::get_time();
		float time_delta_ms = static_cast<float> (current_time - last_time);
		last_time = current_time;
		float dt = time_delta_ms/1000.0f;

		gc.clear(CL_Colorf(1.0f,1.0f,1.0f));

		for(int i=0;i<test_skeleton.get_node_count();i++)
		{
			T2d_vec pos1 = test_skeleton.get_node_data(i).position;
			T2d_vec pos2 = test_skeleton.get_node_parent_data(i).position;
			CL_Draw::line(gc, CL_Pointf(pos1.x, pos1.y), CL_Pointf(pos2.x, pos2.y), CL_Colorf::black);
			CL_Draw::circle(gc, CL_Pointf(pos1.x, pos1.y),3, CL_Colorf::black);
		}
		CL_Console::write_line("fps %1",int(1.0f/dt));
		test_skeleton.step(dt*10.0f,100);

		window.flip(1);
		CL_KeepAlive::process(0);
	}
}

void Tgame::create_window(const CL_Size& size, bool fullscreen)
{
	CL_DisplayWindowDescription window_description;
	window_description.set_title("tokans");
	window_description.set_size(size, true);

	if (fullscreen)
	{
		window_description.set_fullscreen(true);
		window_description.set_decorations(false);
	}

	window = CL_DisplayWindow(window_description);
}